package com.tangbuzhi.prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * 原型模式
 */
public class ProtoType {
    public static class WordDocument implements Cloneable {
        private String text;
        private ArrayList<String> images = new ArrayList<>();

        public WordDocument() {
            System.out.println("constructor start");
        }

        @Override
        protected WordDocument clone() {
            try {
                WordDocument doc = (WordDocument) super.clone();
                doc.text = text;
                doc.images = images;//浅拷贝
                //doc.images = (ArrayList<String>) images.clone();//深拷贝
                return doc;
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
                return null;
            }
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public List<String> getImages() {
            return images;
        }

        public void addImage(String img) {
            images.add(img);
        }

        public void showDocument() {
            System.out.println("text:" + text);
            System.out.print("images:");
            for (int i = 0; i < images.size(); i++) {
                if (i == images.size() - 1) {
                    System.out.print(images.get(i) + "\n");
                } else {
                    System.out.print(images.get(i) + ",");
                }
            }
        }
    }

    public static void main(String[] args) {
        WordDocument originDoc = new WordDocument();
        originDoc.setText("原文档text");
        originDoc.addImage("img1");
        originDoc.addImage("img2");
        originDoc.addImage("img3");
        originDoc.showDocument();
        System.out.println("=========================");

        WordDocument newDoc = originDoc.clone();
        newDoc.showDocument();
        System.out.println("=========================");

        newDoc.setText("修改后的text");
        newDoc.addImage("img4");
        newDoc.showDocument();

        System.out.println("=========================");
        originDoc.showDocument();
        /**
         * 输出结果：
         constructor start
         text:原文档text
         images:img1,img2,img3
         =========================
         text:原文档text
         images:img1,img2,img3
         =========================
         text:修改后的text
         images:img1,img2,img3,img4
         =========================
         text:原文档text
         images:img1,img2,img3,img4

         constructor start
         text:原文档text
         images:img1,img2,img3
         =========================
         text:原文档text
         images:img1,img2,img3
         =========================
         text:修改后的text
         images:img1,img2,img3,img4
         =========================
         text:原文档text
         images:img1,img2,img3
         */
    }
}
